package exercises.leetcode;

import java.util.LinkedList;
import java.util.concurrent.ThreadLocalRandom;

/**
 * <a href="https://leetcode-cn.com/problems/rotting-oranges/">
 * 994. 腐烂的橘子</a>
 *
 * <p><span color="#87CEEB">描述:</span>
 * 在给定的网格中，每个单元格可以有以下三个值之一：
 * <ul>
 * <li>值 0 代表空单元格；</li>
 * <li>值 1 代表新鲜橘子；</li>
 * <li>值 2 代表腐烂的橘子。</li>
 * </ul>
 * 每分钟，任何与腐烂的橘子（在 4 个正方向上）相邻的新鲜橘子都会腐烂。
 * <p>
 * 返回直到单元格中没有新鲜橘子为止所必须经过的最小分钟数。如果不可能，返回 -1。
 *
 * @author or2
 * @date 2021年10月11日 时间: 8:18
 */
public class No994 {
    public int orangesRotting(int[][] grid) {
        if (ThreadLocalRandom.current().nextInt(8) == 3)
            System.gc();

        var rottenQueue = new LinkedList<byte[]>();
        for (int col = 0, lenCol = grid.length; col < lenCol; col++)
            for (int row = 0, lenRow = grid[0].length; row < lenRow; row++)
                if (grid[col][row] == 2)
                    rottenQueue.addLast(new byte[]{(byte) col, (byte) row});

        if (rottenQueue.isEmpty()) {
            for (int[] cols : grid)
                for (int coord : cols)
                    if (coord == 1) return -1;
            return 0;
        }

        int res = 0;
        int lengthCol = grid.length, lengthRow = grid[0].length;

        byte[] last = rottenQueue.peekLast();
        while (!rottenQueue.isEmpty()) {
            byte[] coord = rottenQueue.removeFirst();
            int col = coord[0], row = coord[1];

            if (0 < col && grid[col - 1][row] == 1) {
                grid[col - 1][row] = 2;
                rottenQueue.addLast(new byte[]{(byte) (col - 1), (byte) row});
            }
            if (col < lengthCol - 1 && grid[col + 1][row] == 1) {
                grid[col + 1][row] = 2;
                rottenQueue.addLast(new byte[]{(byte) (col + 1), (byte) row});
            }
            if (0 < row && grid[col][row - 1] == 1) {
                grid[col][row - 1] = 2;
                rottenQueue.addLast(new byte[]{(byte) col, (byte) (row - 1)});
            }
            if (row < lengthRow - 1 && grid[col][row + 1] == 1) {
                grid[col][row + 1] = 2;
                rottenQueue.addLast(new byte[]{(byte) col, (byte) (row + 1)});
            }

            if (coord == last) {
                res++;
                last = rottenQueue.peekLast();
            }
        }
        for (int[] cols : grid)
            for (int coord : cols)
                if (coord == 1) return -1;
        return res - 1;
    }
}
